<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
    {if condition="!empty($isHttps)"}
    <meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests">
    {/if}
    <title>Leaflet位置选择</title>
    <link rel="stylesheet" href="__CDN__/assets/css/bootstrap.min.css"/>
    <link rel="stylesheet" href="__CDN__/assets/css/fastadmin.min.css"/>
    <link rel="stylesheet" href="__CDN__/assets/libs/font-awesome/css/font-awesome.min.css"/>
    <link rel="stylesheet" href="__CDN__/assets/libs/font-awesome/css/font-awesome.min.css"/>
    <link rel="stylesheet" href="__CDN__/assets/addons/wleaflet/leaflet/menu/jquery-accordion-menu.css" />
    <style type="text/css">
        body {
            margin: 0;
            padding: 0;
        }

        #container {
            position: absolute;
            left: 0;
            top: 0;
            right: 0;
            bottom: 0;
        }

        .confirm {
            position: absolute;
            bottom: 30px;
            right: 4%;
            z-index: 99999;
            height: 50px;
            width: 50px;
            line-height: 50px;
            font-size: 15px;
            text-align: center;
            background-color: white;
            background: #1ABC9C;
            color: white;
            border: none;
            cursor: pointer;
            border-radius: 50%;
        }

        .search {
            position: absolute;
            width: 400px;
            top: 0;
            left: 50%;
            padding: 5px;
            margin-left: -200px;
            z-index: 99999;
        }
        .jquery-accordion-menu{
            left: 0 !important;
        }
        .errorText{
            position: fixed;
            z-index: 999999;
            top: 40%;
            left: 41%;
            background: #666666;
            color: #ffffff;
            padding: 10px 20px;
            font-size: 10px;
            border-radius: 10px;
            display: none;
        }

    </style>
</head>
<body>
{if condition="$sel_type eq 'address'"}
<div class="search">
    <div class="input-group">
        <input type="text" id="place" name="q" class="form-control" autocomplete="off" placeholder="输入地点,点击搜索按钮进行搜索" onfocus="$('#amap-ui-poi-picker-sugg-list').show()"/>
        <div class="amap-ui-poi-picker-sugg-container dock-bottom"

             style="position:absolute;max-height: 905px; min-width: 353px; top: 31px; left: 0px;">
            <div class="amap-ui-poi-picker-sugg" >
                <ul class="amap-ui-poi-picker-sugg-list" id="amap-ui-poi-picker-sugg-list" style="display: none">


                </ul>
            </div>
        </div>
        <span class="input-group-btn">
            <button type="submit" name="search" id="search-btn" class="btn btn-success">
                <i class="fa fa-search"></i>
            </button>
        </span>
    </div>
</div>
{/if}
{if condition="$sel_type eq 'line' || $sel_type eq 'polygon'"}
<style>
    .leaflet-left{
        left: 160px !important;
    }
</style>
<div id="jquery-accordion-menu" class="jquery-accordion-menu red">
    <ul id="menu-list">
        <li onclick="return false;">
            <a href="javascript:;" class="showZoom">当前地图级别<span class="submenu-indicator" id="map-zoom">0</span></a>
        </li>
        {if condition="$sel_type eq 'line'"}
        <li ><a href="javascript:;">折线 <span class="submenu-indicator">+</span></a>
            <ul class="submenu">
                <li class="line_click" data-status="add" ><a href="javascript:;">添加折线 </a></li>
                <li class="line_click line_click_edit" data-status="edit" data-type="-1" ><a href="javascript:;">编辑折线 </a></li>
                <li class="line_click" data-status="del" data-type="-1" ><a href="javascript:;">删除折线 </a></li>
            </ul>
        </li>
        {/if}
        {if condition="$sel_type eq 'polygon'"}
        <li ><a href="javascript:;">多边形 <span class="submenu-indicator">+</span></a>
            <ul class="submenu">
                <li class="polygon_click" data-status="add"  ><a href="javascript:;">添加多边形 </a></li>
                <li class="polygon_click polygon_click_edit" data-status="edit" ><a href="javascript:;">编辑多边形 </a></li>
                <li class="polygon_click" data-status="del"  ><a href="javascript:;">删除全部多边形 </a></li>
            </ul>
        </li>
        {/if}
    </ul>
</div>
{/if}
<div class="confirm">确定</div>
<div id="container"></div>
<div class="errorText" id="errorText"></div>
<script src="__CDN__/assets/libs/jquery/dist/jquery.min.js"></script>
<script>
    var isH5loadCssJsUrlData = true;
</script>
<script src="/assets/addons/wleaflet/leaflet/leaflet_common.js"></script>

<script type="text/javascript">
    var as, map, geocoder ,marker,initLeaflet;
    var sel_type = "{$sel_type|default=''}";
    var latlngRes = '{$getParams["latlng"]|default=""}';
    var latlngResArr = [];
    if(latlngRes)
    {
        try{
            if(sel_type == 'line')
            {
                latlngResArr = JSON.parse(latlngRes);
            }else{
                latlngResArr = [];
            }

        }catch (e) {
            console.log('传递数据latlng格式错误')
        }
    }
    var lineObj = {
        latlng:initTextVal(latlngResArr),
        objData:null,
        maxCount:"{$getParams['limit_line_count']|default='0'}"
    };
    var addBorderArr = [];
    var addBorderObj = null;
    //var addBorderObjLatLng = (sel_type == 'polygon' && latlngRes)?initTextVal(JSON.parse(latlngRes)):[];
    var returnObj = {
        lat:"{$getParams['lat']|default=''}",
        lng:"{$getParams['lng']|default=''}",
        address:"{$getParams['address']|default=''}"
    };
    function showError(text) {
        $('#errorText').html(text).show();
        setTimeout(function () {
            $('#errorText').html('').hide();
        },2000)
    }
    function getTextVal(latlng){
        var polygonArr = [];
        if(latlng.length > 0)
        {
            for (var i = 0; i < latlng.length; i++) {
                var info = latlng[i];
                polygonArr.push([info.lat,info.lng]);
            }
        }
        return polygonArr;
    }
    function initTextVal(latlng){
        var polygonArr = [];
        if(latlng.length > 0)
        {
            for (var i = 0; i < latlng.length; i++) {
                var info = latlng[i];
                polygonArr.push({
                    lat:info[0],
                    lng:info[1]
                });
            }
        }
        return polygonArr;
    }
    function getPolygonLatlngRes()
    {
        var getLatLngs = [],
            getLatLngsAll = [],
            latlngResInfo = '';
        if(addBorderArr.length > 0)
        {
            for (var i=0;i<addBorderArr.length;i++)
            {

                if(!addBorderArr[i])
                {
                    continue;
                }
                addBorderObj = addBorderArr[i];//不能删除 删除初始化的latlng无法获取
                getLatLngs = JSON.parse(JSON.stringify(addBorderArr[i].getLatLngs()));
                latlngResInfo = getTextVal(getLatLngs[0]);
                latlngResInfo = (latlngResInfo.length > 0)?JSON.stringify(latlngResInfo):'';
                if(latlngResInfo)
                {
                    getLatLngsAll.push(latlngResInfo);
                }

            }
        }
        if(getLatLngsAll.length > 0)
        {
            latlngRes = getLatLngsAll.join('|');
        }else{
            latlngRes = '';
        }
        //console.log('getPolygonLatlngRes',latlngRes)
        return latlngRes;
    }
    //移除折线
    function setLineObjRemove() {
        if(lineObj.objData)
        {
            lineObj.objData.remove();
            lineObj.objData= null;
        }
        $('.line_click_edit').attr('data-status','edit').find('a').html('编辑折线');
    }
    //显示折线
    function showSetLine() {
        var onValArr = getTextVal(lineObj.latlng);
        if(onValArr.length < 1)
        {
            showError('未设置折线数据');return ;
        }
        lineObj.objData = initLeaflet.plugins_leafletgeoman.createMapPmDraw('Line',onValArr);
    }
    var inputStatus = 0;
    function changeAddress(_this) {
        var _this = $(_this);
        returnObj = {
            lat:_this.attr('data-lat'),
            lng:_this.attr('data-lng'),
            address:_this.attr('data-address')
        };
        createMarker();
        $('#amap-ui-poi-picker-sugg-list').hide();
    }
    function createMarker(obj)
    {
        setObj = obj?obj:returnObj;
        //console.log(setObj)
        if(marker)
        {
            marker.remove();
        }
        var params = {
            bindTooltipContent:setObj.address?setObj.address:'',
            direction:'top',
            needSetView:true
        };
        if(typeof setObj.clickCallback == 'function')
        {
            params.clickCallback = setObj.clickCallback;
        }
        marker = initLeaflet.createMarker({
            lat:setObj.lat,
            lng:setObj.lng
        },params)
    }
    function addBorderObjRemove(index) {
        addBorderObj = addBorderArr[index]?addBorderArr[index]:'';
        if(addBorderObj)
        {
            addBorderObj.remove();
            addBorderObj = null;
            addBorderArr[index] = '';
        }
        var length = 0;
        for (var i=0;i<addBorderArr.length;i++)
        {
            if(addBorderArr[i])
            {
                length++;
            }
        }
        if(length < 1)
        {
            $('.polygon_click_edit').attr('data-status','edit').find('a').html('编辑多边形');
        }
    }
    $(function () {

        var init = function (params) {
            params = params?params:{};
            initLeaflet = wLeaflet.init({
                dom:'container',
                lat:returnObj.lat,
                lng:returnObj.lng,
                maptype:params.maptype?params.maptype:'',
                zoomBase:params.zoom?params.zoom:'',
                zoomSaveFunc(zoom){
                    $('#map-zoom').html(zoom);
                },
                baseLayerChangeFunc:function (e) {
                    //console.log(e)
                    //监听到底层地图改变实践  重新加载地图
                    document.getElementById(e.mapDom).remove();
                    var div = document.createElement('div');
                    div.id = e.mapDom;
                    document.body.append(div);
                    initLeaflet = null;
                    init({
                        maptype:e.changeMapType,
                        zoom:e.zoom
                    });
                    $('.polygon_click_edit').attr('data-status','edit').find('a').html('编辑多边形');
                    $('.line_click_edit').attr('data-status','edit').find('a').html('编辑折线');
                    //init();
                }
            });
            //注册点击事件返回
            initLeaflet.addMapClick(function (clickRes) {
                if(sel_type == 'address')
                {
                    //如果是选择地址
                    initLeaflet.otherApi.getLocationBylatlng(clickRes.latlng,function (res) {
                        if(res.useMapType == "gaodemap")
                        {
                            var formattedAddress = (res.regeocode && res.regeocode.formattedAddress)?res.regeocode.formattedAddress:'';
                        }else if(res.useMapType == 'tiandimap')
                        {
                            var formattedAddress = (res.result && res.result.formatted_address)?res.result.formatted_address:'';
                        }else if(res.useMapType == 'tencentmap')
                        {
                            var formattedAddress = (res.result && res.result.address)?res.result.address:'';
                        }else if(res.useMapType == 'baidumap')
                        {
                            var formattedAddress = (res.address)?res.address:'';
                        }
                        if(formattedAddress)
                        {
                            returnObj = {
                                lat:clickRes.latlng.lat,
                                lng:clickRes.latlng.lng,
                                address:formattedAddress
                            };
                            createMarker(returnObj)
                        }
                    })
                }else if(sel_type == 'marker')
                {
                    latlngRes = JSON.stringify([clickRes.latlng.lat,clickRes.latlng.lng])
                    createMarker({
                        lat:clickRes.latlng.lat,
                        lng:clickRes.latlng.lng,
                        address:latlngRes,
                        clickCallback:function (res) {
                            marker.remove();
                            latlngRes = '';
                        }
                    })
                }

            });
            var latlng = [];
            try{
                if(sel_type == 'polygon')
                {
                    latlngRes = latlngRes?latlngRes.split('|'):'';
                    latlngRes = latlngRes?JSON.stringify(latlngRes):'';
                }

                latlng = latlngRes?JSON.parse(latlngRes):[];

            }catch (e) {

            }
            //初始化启动参数
            switch (sel_type) {
                case 'address':
                    if(returnObj.lat && returnObj.lat > 0 && returnObj.lng && returnObj.lng > 0 && returnObj.address && returnObj.address != '')
                    {
                        setTimeout(function () {
                            createMarker()
                        },100)
                    }
                    break;
                case 'marker':
                    if(latlngRes)
                    {

                        if(latlng[0] && latlng[1])
                        {
                            setTimeout(function () {
                                createMarker({
                                    lat:latlng[0],
                                    lng:latlng[1],
                                    address:latlngRes,
                                    clickCallback:function (res) {
                                        marker.remove();
                                        latlngRes = '';
                                    }
                                })
                            },100)
                        }

                    }
                    break;
                case 'line':
                    if(latlng.length > 0)
                    {
                        setTimeout(function () {

                            lineObj.objData = initLeaflet.plugins_leafletgeoman.createMapPmDraw('Line',latlng);
                        },100)
                    }
                    break;
                case 'polygon':
                    if(latlng.length > 0)
                    {

                        setTimeout(function () {
                            for(var i=0;i<latlng.length;i++)
                            {
                                var latlngInfo = JSON.parse(latlng[i]);
                                //console.log('latlngInfo',JSON.stringify(latlngInfo))
                                addBorderObj = initLeaflet.plugins_leafletgeoman.createMapPmDraw('Polygon',latlngInfo,{
                                    allowSelfIntersection:false,
                                    pathOptionsAddIndex:i,
                                    clickCallback:function(res){
                                        var options = res.options?res.options:{};
                                        var addIndex = -1;
                                        if(options.hasOwnProperty('addIndex') == true)
                                        {
                                            addIndex = options.addIndex;
                                        }
                                        if(addIndex != -1 && confirm('确认删除该多边形?'))
                                        {
                                            addBorderObjRemove(addIndex);
                                            getPolygonLatlngRes();
                                        }else{

                                        }

                                    },
                                });
                                if(typeof addBorderObj.getLatLngs != 'function')
                                {
                                    addBorderObj.latlngInfo = latlngInfo;
                                    addBorderObj.getLatLngs = function(){
                                        var res = [];
                                        res.push(initTextVal(addBorderObj.latlngInfo))
                                        return res;
                                    }
                                }
                                addBorderArr[i] = addBorderObj;
                            }
                            getPolygonLatlngRes();
                        },100)
                    }
                    break;
            }

        };
        $('.polygon_click').click(function () {
            var drawType = 'Polygon';
            initLeaflet.plugins_leafletgeoman.mapPmDisabled(); //禁用折线
            var _this = $(this);
            var status = _this.attr('data-status');
            if(status == 'add')
            {
                //addBorderObjRemove();
                var addIndex = addBorderArr.length;
                initLeaflet.plugins_leafletgeoman.mapPmDraw(drawType,{
                    allowSelfIntersection:false,
                    pathOptionsAddIndex:addIndex,
                    onclickCallBack:function(res){
                        var options = res.options?res.options:{};
                        var addIndex = -1;
                        if(options.hasOwnProperty('addIndex') == true)
                        {
                            addIndex = options.addIndex;
                        }
                        if(confirm('确认删除该多边形?'))
                        {
                            addBorderObjRemove(addIndex);
                            getPolygonLatlngRes
                        }else{

                        }

                    },
                    callback:function (e) {
                        addBorderObj = e.layer;
                        var getLatLngs = addBorderObj.getLatLngs();
                        addBorderArr[addIndex] = addBorderObj;
                        $('#menu-list').find('a').removeClass('nochildAColor');
                        getPolygonLatlngRes();
                        console.log('经纬度列表',getLatLngs)
                    }
                })
            }else if(status == 'edit')
            {

                var canEdit = false;
                for (var i=0;i<addBorderArr.length;i++)
                {
                    var addBorderObj = addBorderArr[i];
                    if(addBorderObj)
                    {
                        canEdit = true;
                        addBorderObj = initLeaflet.plugins_leafletgeoman.mapPmEdit(addBorderObj,{

                        });
                    }

                }
                if(canEdit)
                {
                    _this.attr('data-status','edit-success').find('a').html('编辑完成');
                }else{
                    showError('未设置多边形');return false;
                }

            }
            else if(status == 'edit-success')
            {
                for (var i=0;i<addBorderArr.length;i++)
                {
                    var addBorderObj = addBorderArr[i];
                    if(addBorderObj)
                    {
                        initLeaflet.plugins_leafletgeoman.mapPmEditFinish(addBorderObj,{
                            callback:function (e) {
                                addBorderObj = e.layer;
                                //console.log('addBorderObj',addBorderObj)
                                var getLatLngs = addBorderObj.getLatLngs();
                                console.log('经纬度列表',getLatLngs)
                                addBorderArr[i] = addBorderObj;
                            }
                        })
                    }
                }
                getPolygonLatlngRes();
                $('#menu-list').find('a').removeClass('nochildAColor');
                _this.attr('data-status','edit').find('a').html('编辑多边形');
            }else if(status == 'del')
            {
                var length = addBorderArr.length;
                if(length > 0 )
                {
                    for (var i=0;i<length;i++)
                    {
                        addBorderObjRemove(i);
                    }
                }
                //addBorderObjRemove();
            }
        })
        //绘制折线
        $('.line_click').click(function () {

            var status = $(this).attr('data-status');
            if(status == 'del')
            {
                setLineObjRemove();
                lineObj.latlng = ''; //同时清空返回的经纬度
                wLeaflet.plugins_leafletgeoman.mapPmDisabled();
            }
            else if(status == 'edit')
            {
                if(lineObj.objData == null)
                {
                    showError('未获取到折线数据');
                    return ;
                }
                $(this).attr('data-status','edit-success').find('a').html('编辑完成');
                var nowObj = lineObj.objData;
                initLeaflet.plugins_leafletgeoman.mapPmEdit(nowObj,{

                })
            }else if(status == 'edit-success')
            {
                $(this).attr('data-status','edit').find('a').html('编辑折线');
                var nowObj = lineObj.objData;
                initLeaflet.plugins_leafletgeoman.mapPmEditFinish(nowObj,{
                    callback:function (e) {
                        let layer = e.layer;
                        let getLatLngs = JSON.parse(JSON.stringify(layer.getLatLngs()));
                        if(lineObj.maxCount > 0 && getLatLngs.length > lineObj.maxCount)
                        {
                            showError('最多只能有'+lineObj.maxCount+'个点位');
                            setLineObjRemove();
                            showSetLine();
                            return ;
                        }else{
                            lineObj.objData = layer;
                            lineObj.latlng = getLatLngs;
                            latlngRes = getTextVal(lineObj.latlng);
                            latlngRes = (latlngRes.length > 0)?JSON.stringify(latlngRes):'';
                            console.log('正确',lineObj)
                        }

                        //console.log(setScopePolyline.getLatLngs());
                    }
                });
            }
            else if(status == 'add')
            {
                setLineObjRemove();
                initLeaflet.plugins_leafletgeoman.mapPmDraw('Line',{
                    allowSelfIntersection:false,
                    drawMaxCount:lineObj.maxCount,
                    callback:function (e) {
                        let layer =  e.layer;
                        let getLatLngs = JSON.parse(JSON.stringify(layer.getLatLngs()));
                        lineObj.objData = layer;
                        lineObj.latlng = getLatLngs;
                        latlngRes = getTextVal(lineObj.latlng);
                        latlngRes = (latlngRes.length > 0)?JSON.stringify(latlngRes):'';
                    }
                })

            }
        })
        /**
         * 搜索事件
         */
        $('#place').bind('keyup', function(event) {
            if (event.keyCode == "13") {
                $('#search-btn').click();
            }
        });
        $('#search-btn').click(function () {
            var val = $('#place').val();
            if(!val){
                $('#amap-ui-poi-picker-sugg-list').show().html(`<li class="sugg-item ">
                        <span class="sugg-name">请输入搜索值</span>
                    </li>`)
                return ;
            }
            initLeaflet.otherApi.getLocationSearch(val,function (res) {
                $('#amap-ui-poi-picker-sugg-list').show().html('');
                var getPois = res.datalist;
                if(!getPois || getPois.length < 1)
                {
                    $('#amap-ui-poi-picker-sugg-list').html(`<li class="sugg-item ">
                        <span class="sugg-name">没有对应的搜索结果</span>
                    </li>`);return ;
                }
                for (var i=0;i<getPois.length;i++)
                {
                    var lonlat = getPois[i].latlng;
                    $('#amap-ui-poi-picker-sugg-list').append(`<li class="sugg-item"
                                data-lng="${lonlat.lng}"
                                data-lat="${lonlat.lat}"
                                data-address = "${getPois[i].name}"
                                onclick="changeAddress(this)">
                            <span class="sugg-name">${getPois[i].name}</span>
                        </li>`);
                }
            });
        })

        //点击确定后执行回调赋值
        var close = function (data) {
            var index = parent.Layer.getFrameIndex(window.name);
            var callback = parent.$("#layui-layer" + index).data("callback");
            //再执行关闭
            parent.Layer.close(index);
            //再调用回传函数
            if (typeof callback === 'function') {
                callback.call(undefined, data);
            }
        };

        //点击搜索按钮
        $(document).on('click', '.confirm', function () {
            switch (sel_type) {
                case 'address':
                    returnObj.zoom = initLeaflet.getMapInfo('getZoom');
                    close(returnObj);
                    break;
                case 'marker':
                    //选择marker点
                    close({
                        latlng:latlngRes
                    })
                    break;
                case 'line':
                    if(lineObj.latlng)
                    {
                        latlngRes = getTextVal(lineObj.latlng);
                        latlngRes = (latlngRes.length > 0)?JSON.stringify(latlngRes):'';
                    }else{
                        latlngRes = '';
                    }
                    close({
                        latlng:latlngRes
                    })
                    break;
                case 'polygon':
                    //选择marker点
                    latlngRes = getPolygonLatlngRes();
                    close({
                        latlng:latlngRes
                    })
                    break;
                default:
                    break;
            }


        });
        init();
        $('#menu-list').find('li').click(function (e) {
            if($(this).attr('onclick'))
            {
                return false;
            }
            e.stopPropagation();
            e.preventDefault();
            var defaults = {
                speed: 300,
                showDelay: 0,
                hideDelay: 0,
                singleOpen: true,
                clickEffect: true
            };
            $('#menu-list').find('a').removeClass('nochildAColor');
            if ($(this).children(".submenu").length > 0) {
                type = -1; //点击左侧按钮的时候 清除地图的单机事件
                initLeaflet.plugins_leafletgeoman.mapPmDisabled(); //清空地图的绘画事件
                if ($(this).children(".submenu").css("display") == "none") {
                    $(this).children(".submenu").delay(defaults.showDelay).slideDown(defaults.speed);
                    $(this).children(".submenu").siblings("a").addClass("submenu-indicator-minus");
                    if (defaults.singleOpen) {
                        $(this).siblings().children(".submenu").slideUp(defaults.speed);
                        $(this).siblings().children(".submenu").siblings("a").removeClass("submenu-indicator-minus")
                    }
                    return false
                } else {
                    $(this).children(".submenu").delay(defaults.hideDelay).slideUp(defaults.speed)
                }
                if ($(this).children(".submenu").siblings("a").hasClass("submenu-indicator-minus")) {
                    $(this).children(".submenu").siblings("a").removeClass("submenu-indicator-minus")
                }
            }else{
                $(this).find('a').addClass('nochildAColor');
            }
        })
    });
</script>
</body>
<style>
    .ui-poi-picker-sugg-container {
        position: absolute;
        -webkit-box-sizing: border-box;
        box-sizing: border-box;
        padding: 0;
        overflow: auto;
        z-index: 9999;
    }
    .amap-ui-poi-picker-sugg-container {
        border: 1px solid #ccc;
        background: #fff;
    }
    .amap-ui-poi-picker-sugg-list {
        margin: 0;
        padding: 0;
    }
    ul{
        list-style-type:none;
    }
    .amap-ui-poi-picker-sugg-list .sugg-item {
        margin: 0;
        border-bottom: 1px solid #eee;
        font-size: 1em;
        padding: 7px 5px 7px 23px;
        background: url(http://webapi.amap.com/ui/1.0/ui/misc/PoiPicker/assets/poi.png) no-repeat 5px 50%;
        vertical-align: middle;
        cursor: pointer;
    }
    .amap-ui-poi-picker-sugg-list .sugg-item.sugg-no-id {
        background: url(http://webapi.amap.com/ui/1.0/ui/misc/PoiPicker/assets/search.png) no-repeat 5px 50%;
    }
    .amap-ui-poi-picker-sugg-list .sugg-district {
        font-size: 90%;
        color: #999;
        margin-left: 5px;
    }
    .amap-ui-poi-picker-sugg-list .sugg-address {
        display: none;
    }
</style>
</html>